<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <h2>sse测试</h2>
    <div>
      <div id="tokenDiv"></div>
      <p>
        用户名：<input type="text" value="relax" id="username" /><br />
        密码：<input type="password" value="123456" id="password" /><br />
      </p>
      <p><input type="button" value="获取token" onclick="getToken()" /></p>
      <div id="tokenDiv"></div>
      <p><input type="button" value="测试sse" onclick="sseTest()" /></p>
      <div id="showAlarmInfo"></div>
    </div>
    <script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-3.6.0.min.js"></script>
    <script>
      function getToken() {
        var settings = {
          url: "http://localhost:8888/login",
          method: "POST",
          timeout: 0,
          headers: {
            "User-Agent": "Apifox/1.0.0 (https://apifox.com)",
            "Content-Type": "application/json",
            Accept: "*/*",
            Host: "localhost:8888",
            Connection: "keep-alive",
          },
          data: JSON.stringify({
            username: $("#username").val(),
            password: $("#password").val(),
          }),
        };

        $.ajax(settings).done(function (res) {
          console.log(res);
          $("#tokenDiv").text(res.data);
        });
      }

      function displayAlarmNotification(alarm){
        $('#showAlarmInfo').append("<br>" + JSON.stringify(alarm));
      }

      function sseTest() {
        let token = $("#tokenDiv").text() || "";
        if (!token) {
          alert("请先获取token");
          return;
        }
        const eventSource = new EventSource(
          "http://localhost:8888/sse/subscribe?token=" + token
        );

        eventSource.onopen = function () {
          console.log("Connected to SSE");
        };

        eventSource.onerror = function (err) {
          console.error("SSE error:", err);
        };

        eventSource.onmessage = function (event) {
          const alarm = JSON.parse(event.data);
          console.log("Received alarm:", alarm);
          // 在页面上展示报警信息
          displayAlarmNotification(alarm);
        };
      }
    </script>
  </body>
</html>
